import { UploadOutlined, SearchOutlined, CloudUploadOutlined, BarChartOutlined } from '@ant-design/icons';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import { Button, message, Upload, Input, Table, Space, TablePaginationConfig, Popconfirm } from 'antd';
import React, { useEffect, useState } from 'react';
import { xlsxFormate } from "@/utils/xlsxFile"
import type { ColumnsType } from 'antd/es/table';
import { getListAct, putExcelAct, deleteExcelAct } from '@/redux/actions/Excel';
import "./index.less"
import { useDispatch, useSelector } from 'react-redux';
import { ReducersType } from '@/redux/store';
import { AxiosResponse } from 'axios';
import { handlerBread } from '@/redux/actions';


const map = {
    '编号': 'id',
    '姓名': 'name',
    '体重': 'weight',
    '年龄': 'age',
    '成绩': 'achievement',
    '账号': 'account'
}





let pageData = {
    page: 1,
    pageSize: 10,
    name: ''
}

const BreadData: breadType[] = [
    {
        label: "综合案例",
        icon: <BarChartOutlined />,
        herf: ''
    },
    {
        label: "Excel 导入",
        icon: undefined,
        herf: ''
    }
]

export default function Form2() {
    const [uploading, setUploading] = useState(false);
    const dispatch = useDispatch()




    //获取数据列表

    const data = useSelector((state: ReducersType) => {
        return state.ExcelReducer
    })
    
    let initPage = ()=>{
        pageData = {
            page: 1,
            pageSize: 10,
            name: ''
        }
        setPageOption({ ...pageConfig, pageSize: 10 , current: 1})
    }

    const getList = (page = 1, pageSize = 10) => {
        dispatch(getListAct(pageData)).then((res: AxiosResponse<any, any> | string) => {
            if (res == "error") {
                message.error("加载数据失败,请稍后再试")
            } else {
                setPageOption({ ...pageOption, total: (res as AxiosResponse<any, any>).count, pageSize, current: page })
                setLoading(false)
            }
        })
    }

    const PageChange = (page: number, pageSize: number) => {
        pageData.page = page
        pageData.pageSize = pageSize
        getList(page, pageSize)
    }
    useEffect(() => {
        initPage()
        getList()
        dispatch(handlerBread(BreadData))
    }, [])

    let pageConfig: TablePaginationConfig = {
        position: ['bottomRight'],
        defaultCurrent: 1,
        total: 0,
        showTotal: (total) => `共 ${total} 条`,
        pageSizeOptions: [10, 20, 30, 40, 50],
        showSizeChanger: true,
        showQuickJumper: true,
        onChange: PageChange,
        defaultPageSize: 10,
        pageSize: 10,
        current: 1
    }

    const [pageOption, setPageOption] = useState(pageConfig)



    //撒上传Excel 批量导入
    const props: UploadProps = {
        beforeUpload: (file) => {

            handlerExcel(file)
            return false;
        },

        showUploadList: false
    };

    const handlerExcel = (file: File) => {
        let name = file.name
        let suffix = name.substr(name.lastIndexOf("."));

        if (".xls" != suffix && ".xlsx" != suffix) {
            message.error("选择Excel格式的文件导入！");
            return false;
        }
        setUploading(true)
        xlsxFormate(file, map).then(async (res) => {
            putExcelAct(res).then((result) => {
                if (result == 'success') {
                    message.success("导入成功")
                    getList()

                } else {
                    message.error("导入失败")
                }
                setUploading(false)
            })
        })
    }

    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);


    const onSelectChange = (newSelectedRowKeys: React.Key[], selectedRows: any) => {
        // console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        // console.log("selectRowkeys Row", selectedRows);

        setSelectedRowKeys(newSelectedRowKeys);
    };

    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };

    const handlerExcelDelete = () => {
        deleteExcelAct(selectedRowKeys).then((res: AxiosResponse<any, any>) => {
            if (res.code == 1) {
                message.success("删除成功")
                getList()
            } else {
                message.error(res.msg || "删除失败")
            }
        })
    }

    const columns: ColumnsType<studentType> = [
        {
            title: '姓名',
            dataIndex: 'name',
            width: 300
        },
        {
            title: '年龄',
            dataIndex: 'age',
        },
        {
            title: '账号',
            dataIndex: 'account',
        },
        {
            title: '体重',
            dataIndex: 'weight',
        }, {
            title: '成绩',
            dataIndex: 'achievement',
        }, {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <a className='edit' key={record.id} onClick={handlerEdit} >编辑</a>
                    <Popconfirm
                         title="提示"
                         description="该操作会导致永久删除该数据,并不可逆,是否删除?"
                         onConfirm={()=> handleOk(record)}
                         onCancel={handleCancel}
                         okText="确定"
                         cancelText="取消"
                    >
                        <a className='delete' key={record.id} href="#" >删除</a>
                    </Popconfirm>
                </Space>
            )
        },
    ];
    //删除
    const [confirmLoading, setConfirmLoading] = useState(false);


    const handleOk = (e: studentType) => {
        setConfirmLoading(true);
        deleteExcelAct([e.id]).then((res:AxiosResponse<any, any>)=>{
            if (res.code == 1) {
                message.success("删除成功")
                getList()
            } else {
                message.error(res.msg || "删除失败")
            }
            setConfirmLoading(false);
        })
    };

    const handleCancel = () => {
        message.info("取消了删除操作")
    };

    const handlerEdit = ()=>{
        message.info("暂未开发...")
    }

   const handlerSearch = (e:any)=>{
       pageData.name = e.target.value
       getList()
   }
   const [loading, setLoading] = useState(true)

   


    return (
        <div className="Form2">
            <div className='header flex_a'>
                <Input size="middle" placeholder="请输入姓名" prefix={<SearchOutlined />} style={{ width: 250 }} allowClear onPressEnter={handlerSearch} />
                <Upload {...props} className={"upBtn"} >
                    <Button size="middle" type="primary" icon={<CloudUploadOutlined />} loading={uploading}>Excel导入</Button>
                </Upload>
                <Button type='primary' danger className={"deleteBtn"} onClick={handlerExcelDelete}>批量删除</Button>
            </div>
            <div className='Table'>
                <Table rowSelection={rowSelection} columns={columns} dataSource={data} pagination={pageOption} rowKey={item => item.id} loading={loading} />
            </div>
        </div>
    )
}